//
//  LJMainTabBar.swift
//  LJWeibo
//
//  Created by Raymond on 15/12/15.
//  Copyright © 2015年 liu. All rights reserved.
//

import UIKit


class LJMainTabBar: UITabBar {
    
    // 底部item数量
    private let count = 5
    
    /// 按钮点击闭包
    var composeClicked: (() -> ())?
    
    init(composeClicked: (() -> ())?){
        super.init(frame: CGRectZero)
        self.composeClicked = composeClicked
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        //item宽度
        let width = self.bounds.width / CGFloat(count)
        
        //计算最左边item的frame
        let leftItemFrame = CGRect(x: 0, y: 0, width: width, height: self.bounds.height)
        
        var index = 0
        
        //遍历子控件
        for item in subviews {
            if item is UIControl && !(item is UIButton) {
                item.frame = CGRectOffset(leftItemFrame, CGFloat(index) * width, 0)

                //遍历到第三个时加2
                    index += index == 1 ? 2 : 1
            }
        }
        composeButton.frame = CGRectOffset(leftItemFrame, 2.0 * width, 0)
        
    }
    
    @objc private func composeButtonDidClick() {
        composeClicked?()
    }
    
    //MARK - 懒加载
    lazy var composeButton: UIButton = {
        let button = UIButton()
        
        //设置背景图片
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        //添加
        self.addSubview(button)
        
        button.addTarget(self, action: "composeButtonDidClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()

}
